package jsontest;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class JSONTest {

    public static void main(String... args) throws JSONException, IOException {
        final JSONObject res = new JSONObject();
        //adding value in JSON object
        JSONArray jarray = new JSONArray();
        for (int i = 0; i < 3; i++) {
            JSONObject ob = new JSONObject();
            ob.put("k1" + i, "v1" + i);
            ob.put("k2" + i, "v2" + i);
            jarray.put(ob);
        }
        res.put("res", jarray);
        System.out.println("structure of created json object:" + res);
        //retrieving value from JSON object element wise
        System.out.println("retrieving value from JSON object element wise");
        JSONArray output = res.getJSONArray("res");
        for (int i = 0; i < output.length(); i++) {
            JSONObject ob = output.getJSONObject(i);
            System.out.print(ob.get("k1" + i));
            System.out.println(ob.get("k2" + i));
        }

        person p = new person(1, "ssss");
        List<String> hobbis = new ArrayList<>();
        hobbis.add("eat");
        hobbis.add("run");
        p.setHobbis(hobbis);
        System.out.println("s==================");
        System.out.println(JSON.toJSONString(p));

        ObjectMapper objectMapper = new ObjectMapper();

        String s = "{\"age\":1,\"hobbis\":[\"eat\",\"run\"],\"name\":\"ssss\"}";
        System.out.println("objectMapper==>" + objectMapper.readValue(s, person.class).getName());
        person pp = JSON.parseObject(s, person.class, null);
        System.out.println("JSON.parseObject==>" + pp.getName());

        objectMapper.writeValue(new File("/Users/dingjianfeng/IdeaProjects/GitTest/src/main/java/jsontest/test.json"), pp);


    }
}

class person {

    private int age;
    private String name;
    private List<String> hobbis = new ArrayList<>();

    public person() {
    }

    public person(int age, String name) {
        this.age = age;
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<String> getHobbis() {
        return hobbis;
    }

    public void setHobbis(List<String> hobbis) {
        this.hobbis = hobbis;
    }
}